﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Model.Message;
using IMClient.Model.UI;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Windows;
using IMClient.Config;
using IMClient.Model;
using IMClient.Model.DTO;
using IMClient.WebSocketService;
using System.Text.RegularExpressions;

namespace IMClient.ViewModels
{
    public partial class GroupNotificationViewModel : ObservableObject
    {
        private readonly HttpClient _httpClient;

        [ObservableProperty] private ObservableCollection<GroupNotification> notificationList = new();

        public static event Action<string, string>? GroupAvatarUpdated;
        public static event Action<string, string>? GroupNameUpdated;
        public GroupNotificationViewModel()
        {
            _httpClient = new HttpClient();
            WebSocketConnection.OnMessageReceived += OnMessageReceived;
        }

        // 接收到WebSocket消息时的处理方法
        private void OnMessageReceived(BaseMessage message)
        {
            if (message is JoinGroupRequest joinGroupRequest)
            {
                Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    NotificationList.Insert(0, new GroupNotification
                    {
                        Name = joinGroupRequest.SenderName,
                        Avatar = joinGroupRequest.SenderAvatar,
                        SenderId = joinGroupRequest.SenderId,
                        Action = $"请求加入{joinGroupRequest.GroupName}群组",
                        GroupId = joinGroupRequest.GroupId,
                        GroupCreator = joinGroupRequest.GroupCreator,
                        GroupName = joinGroupRequest.GroupName,
                        GroupAvatar = joinGroupRequest.GroupAvatar,
                        Time = DateTime.Now.ToString("yyyy/MM/dd"),
                        Message = $"留言：{joinGroupRequest.Description}",
                        Status = "待处理",
                        RequestMessageId = joinGroupRequest.MessageId
                    });
                });
            }
            else if (message is JoinGroupResponse joinGroupResponse)
            {
                // 处理好友请求响应
                Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    var notification = NotificationList.FirstOrDefault(n =>
                        n.GroupId == joinGroupResponse.GroupId);

                    if (notification != null)
                    {
                        notification.Status = joinGroupResponse.Accepted ? "对方已同意" : "对方已拒绝";

                        if (joinGroupResponse.Accepted)
                        {
                            ChatWindowViewModel.Instance.GetContactsViewModel()?.JoinGroupAccept(
                                User.UserId ?? throw new InvalidOperationException(),
                                new GroupViewModel
                                {
                                    Id = joinGroupResponse.GroupId,
                                    Name = joinGroupResponse.GroupName,
                                    Creator = joinGroupResponse.GroupCreator,
                                    Avatar = joinGroupResponse.GroupAvatar
                                });
                        }
                    }
                });
            }
            else if (message is InitialGroupNotification initialGroupNotification){
                Application.Current.Dispatcher.BeginInvoke(() => {ChatWindowViewModel.Instance.GetContactsViewModel()?.JoinGroupAccept(
                    User.UserId ?? throw new InvalidOperationException(),
                    new GroupViewModel
                    {
                        Id = initialGroupNotification.GroupId,
                        Name = initialGroupNotification.GroupName,
                        Creator = initialGroupNotification.Creator,
                        Avatar = initialGroupNotification.GroupAvatar
                    });
                });
            }
            else if(message is GroupAvatarUpdateNotification groupAvatarUpdateNotification)
            {
                GroupAvatarUpdated?.Invoke(groupAvatarUpdateNotification.GroupId, groupAvatarUpdateNotification.GroupAvatar);
            }
            else if(message is GroupNameUpdateNotification groupNameUpdateNotification)
            {
                GroupNameUpdated?.Invoke(groupNameUpdateNotification.GroupId, groupNameUpdateNotification.GroupName);
            }
        }

        [RelayCommand]
        private async Task AcceptJoinGroupRequest(GroupNotification notification)
        {
            await HandleJoinGroupRequest(notification, true);
        }

        [RelayCommand]
        private async Task RejectJoinGroupRequest(GroupNotification notification)
        {
            await HandleJoinGroupRequest(notification, false);
        }

        private async Task HandleJoinGroupRequest(GroupNotification notification, bool accepted)
        {
            try
            {
                // 构造请求体
                var requestData = new JoinGroupResponse
                {
                    SenderId = User.UserId ?? throw new InvalidOperationException(),
                    SenderName = User.UserName ?? throw new InvalidOperationException(),
                    SenderAvatar = User.UserAvatar,
                    ReceiverId = notification.SenderId!,
                    Content = accepted ? $"已同意加入{notification.Name}群组" : $"已拒绝加入{notification.Name}群组",
                    GroupId = notification.GroupId!,
                    GroupName = notification.GroupName!,
                    GroupAvatar = notification.GroupAvatar!,
                    GroupCreator = notification.GroupCreator,
                    RequestMessageId = notification.RequestMessageId,
                    Accepted = accepted,
                };

                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(
                    $"{NetWorkConfig.BaseUrl}/group/joinresponse",
                    content
                );

                if (response.IsSuccessStatusCode)
                {
                    // 更新UI状态
                    notification.Status = accepted ? "已同意" : "已拒绝";
                }
                else
                {
                    var error = await response.Content.ReadFromJsonAsync<ErrorResponse>();
                    throw new Exception(error?.Message ?? "处理群组请求失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理群组请求失败：{ex.Message}");
                // 可能需要回滚UI状态
                notification.Status = "待处理";
            }
        }


        // 将主动请求添加群组通知
        public void JoinGroupRequest(GroupNotification notification)
        {
            NotificationList.Insert(0, notification);
        }
    }
}